//
//  UserAccount.swift
//  FWSinaWeibo
//
//  Created by 范伟 on 16/2/25.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import UIKit
private let FWWeiboUserAccountKey = "cn.itcast.userAccount"
class UserAccount: NSObject {
    /// 用户账户单例，全局入口
    static let sharedInstance = UserAccount()
    /// 用户是否登陆标记
    var isLogin: Bool {
        return access_token != nil
    }
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数，不是`string`
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid: String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    override var description: String {//Computed property must have a explicit type
        let keys = ["access_token", "expires_in", "uid", "screen_name", "avatar_large", "expiresDate"]
        return dictionaryWithValuesForKeys(keys).description
    }
    /**
     私有化构造方法，只开放全局入口创建单例对象
     */
    private override init() {
        super.init()
        
        loadUserAccount()
    }
    init(dict: [String: AnyObject]) {
        super.init()
        /**
        *  kvc
        */
        setValuesForKeysWithDictionary(dict)
    }
    /**
     Invoked by setValue:forKey: when it finds no property for a given key.
     
     - parameter value: <#value description#>
     - parameter key:   <#key description#>
     */
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
}

extension UserAccount {
    /**
     使用字典更新用户账户数据
     
     - parameter dict: 字典
     */
    func updateUserAccount(dict: [String: AnyObject]) {
        setValuesForKeysWithDictionary(dict)
        saveUserAccount()
    }
    /**
     保存用户账户信息到用户偏好
     */
    func saveUserAccount() {
        let keys = ["access_token", "expiresDate", "uid", "screen_name", "avatar_large"]
        let dict = dictionaryWithValuesForKeys(keys)
//        NSUserDefaults.standardUserDefaults().setValuesForKeysWithDictionary(dict)
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey: FWWeiboUserAccountKey)
        print(NSHomeDirectory())
    }
    
    private func loadUserAccount() {
        let object: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(FWWeiboUserAccountKey)
        //从用户偏好中加载用户账户信息
        guard let dict = object as? [String: AnyObject] else {
            return
        }
        setValuesForKeysWithDictionary(dict)
        //判断令牌是否过期，如果过期，将令牌设置为 nil
        if isExpired {
            print("令牌已经过期!")
            access_token = nil
        } else {
            print("令牌正常!")
        }
    }
    /// 判断令牌是否过期
    private var isExpired: Bool {
        //过期时间比较系统当前时间，如果结果为升序就表示过期了
        return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
}
